#include "SList.h"

SLTNode* BuySLTNode(SLDataType x) {
	SLTNode* s = (SLTNode*)malloc(sizeof(SLTNode));
	if (s == NULL) {
		perror("malloc fail");
		exit(-1);
	}
	s->data = x;
	s->next = NULL;
	return s;
}
SLTNode* CreateSList(int n) {
	SLTNode* phead = NULL, *ptail = NULL;
	for (int i = 0; i < n; i++) {
		SLTNode* newnode = BuySLTNode(i + 10);
		if (phead == NULL) {
			phead = ptail = newnode;
		}
		else {
			ptail->next = newnode;
			ptail = newnode;
		}
	}
	return phead;
}
void SLTPrint(SLTNode* Phead) {

	
	while (Phead != NULL) {
		printf("%d ", Phead->data);
		Phead = Phead->next;
	}
	printf("NULL\n");
}
void SLTPushBack(SLTNode** pphead, SLDataType x) {
	if (*pphead == NULL) {
		*pphead = BuySLTNode(x);
	}
	else {
		SLTNode* ptail = *pphead;
		while (ptail->next != NULL) {
			ptail = ptail->next;
		}
		ptail->next = BuySLTNode(x);
	}
}
void SLTPopBack(SLTNode** pphead) {
	assert(*pphead);
	SLTNode* ptail = *pphead;
	if (ptail->next == NULL) {
		free(*pphead);
		*pphead = NULL;
	}
	else {
		SLTNode* prve = NULL;
		while (ptail->next != NULL) {
			prve = ptail;
			ptail = ptail->next;
		}
		free(ptail);
		prve->next = NULL;
	}
	
}
void SLTPushFront(SLTNode** pphead, SLDataType x) {
	SLTNode* newnode = BuySLTNode(x);
	newnode->next = *pphead;
	*pphead = newnode;
}
void SLTPopFront(SLTNode** pphead) {
	assert(*pphead);
	SLTNode* head = (*pphead)->next;
	free(*pphead);
	*pphead = head;
}

SLTNode* SLTFind(SLTNode* phead, SLDataType x) {
	SLTNode* cur = phead;
	while (cur) {
		if (cur->data == x) {
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void SLTInsertAfter(SLTNode* pos, SLDataType x) {
	assert(pos);
	SLTNode* next = pos->next;
	pos->next = BuySLTNode(x);
	pos->next->next = next;
}
void SLTInsert(SLTNode** pphead, SLTNode* pos, SLDataType x) {
	assert(pos);
	if (*pphead == pos) {
		SLTPushFront(pphead, x);
	}
	else {
		SLTNode* newnode = *pphead;
		while (newnode->next != pos) {
			newnode = newnode->next;
		}
		newnode->next=BuySLTNode(x);
		newnode->next->next = pos;
	}
}
void SLTEraseAfter(SLTNode* pos) {
	assert(pos);
	if (pos->next != NULL) {
		SLTNode* next = pos->next;
		pos->next = next->next;
		free(next);
	}
}
void SLTDestory(SLTNode** pphead) {
	SLTNode* cur = *pphead;
	while (cur) {
		SLTNode* nextnode = cur->next;
		free(cur);
		cur = nextnode;
	}
	*pphead = NULL;
}